package com.pengtu.gsj.controller.system;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pengtu.gsj.controller.base.BaseController;
import com.pengtu.gsj.entity.app.Sysmenu;
import com.pengtu.gsj.interceptor.Token;
import com.pengtu.gsj.service.system.SysmenuManagerService;
import com.pengtu.gsj.utils.web.SpringMvcUtils;
/** 
 * @author zl 
 * @version 创建时间：2017年4月5日 下午5:47:39 
 * 类说明 
 */
/** 
 * @author zl 
 * @version 创建时间：2017年4月5日 下午5:47:39 
 * 类说明 
 */
 @Controller
 @RequestMapping("/systemMenu/")
public class SystemMenuController extends BaseController {
	 
	 @Autowired
	 private SysmenuManagerService sysmenuManagerService;
	 
	 /**
		 * 
		 * loadEntity:
		 * 适用: 每个方法执行之前都会执行该方法
		 * @param id  sysmenu主键id
		 * @return 返回持久对象sysmenu或者新创建对象
		 * @exception 
		 * @since  1.0.0
		 */
		@ModelAttribute
		public void loadEntity(String id, Model model){
			Sysmenu sysmenu ;
			if (StringUtils.isNotEmpty(id)) {
				sysmenu = sysmenuManagerService.get(id);
			}else {
				sysmenu = new Sysmenu();
			}
			model.addAttribute("sysmenu", sysmenu);
			model.addAttribute("top", SpringMvcUtils.getParameter("top"));
			model.addAttribute("left", SpringMvcUtils.getParameter("left"));
		}

	 /**
	  * @desc 作用在新增和修改菜单信息时，主要是根据id或者parentId得到菜单实体再进行页面跳转
	  * @param id   菜单主键id
	  * @param model  传递参数到页面
	  * @return 返回到菜单修改/修改页面
	  */
	 @RequestMapping("input")
	 @Token(save = true)
	 public String systemMenuInput(@ModelAttribute Sysmenu sysmenu,Model model){
		String type = SpringMvcUtils.getParameter("type"); 
		String parentId = SpringMvcUtils.getParameter("parentId");
		Sysmenu parentSysmenu;
		if (StringUtils.isNotEmpty(parentId)) {
			parentSysmenu = sysmenuManagerService.get(parentId);
			sysmenu.setParent(parentSysmenu);
		}
		if ("1".equals(type)) {
			return "system/roadSysmenu_input";
		} else {
			return "system/sysmenu_input";
		}
		
	 }
	 
	 @ResponseBody
	 @RequestMapping(value="treeData",produces = "application/json; charset=utf-8")
	 public List<Map<String, Object>> treeData(HttpServletRequest request){
		 	String type = SpringMvcUtils.getParameter("type"); 
			List<Map<String, Object>> mapList = Lists.newArrayList();
//			List<Sysmenu> list = sysmenuManagerService.getAll();
			List<Sysmenu> list = Lists.newArrayList();
			if ("1".equals(type)) {
				list = sysmenuManagerService.getRoadSysmenus();
			} else {
				list = sysmenuManagerService.getAllSysmenus();
			}
			 
			String extId = request.getParameter("extId");
			for (int i=0; i<list.size(); i++){
				Sysmenu e = list.get(i);
				if (extId == null || (extId!=null && !extId.equals(e.getId()) 
						&& e.getParentIds().indexOf(","+extId+",")==-1)){
					Map<String, Object> map = Maps.newHashMap();
					map.put("id", e.getId());
					map.put("pId", e.getParent()!=null?e.getParent().getId():0);
					map.put("name", e.getName());
					mapList.add(map);
				}
			}
			return mapList;
		}
	 
	 /**
	  * @desc  主要使用在菜单列表页面
	  * @param request  页面请求
	  * @param model   传递参数到页面
	  * @return  返回到菜单列表页面
	  */
	 @RequestMapping(value="list")
	 public String getSysmenuList(HttpServletRequest request,Model model){
		 	String msg = SpringMvcUtils.getParameter("msg");
		 	String type = SpringMvcUtils.getParameter("type");
			if (StringUtils.isNotEmpty(msg)) {
				model.addAttribute("msg", msg);
			}
		 	List<Sysmenu> list = Lists.newArrayList();
//		 	List<Sysmenu> sourcesList = sysmenuManagerService.getAll();
		 	List<Sysmenu> sourcesList = Lists.newArrayList(); 
		 	if ("1".equals(type)) {
		 		sourcesList = sysmenuManagerService.getRoadSysmenus();
			} else {
				sourcesList = sysmenuManagerService.getAllSysmenus();
			}
		 			
		 	Sysmenu topSysmenu = sysmenuManagerService.getTopMenu();
		 	Sysmenu.sortList(list, sourcesList, topSysmenu.getId());
		 	model.addAttribute("topMenuId", topSysmenu.getId());
		 	model.addAttribute("list", list);
		 	
		 	System.out.println("1".equals(type));
		 	if ("1".equals(type)) {
		 		return "system/road_sysmenu";
			} else {
				return "system/sysmenu";
			}
			
	 }
	 
	 
	 /**
	  * @dec  该方法主要使用在新增和修改菜单信息时，表单提交之后的操作处理
	  * @param sysmenu 接受新增/修改页面表单参数
	  * @param model   传递业务操作结束之后的提示信息
	  * @return   重定向到菜单列表页面
	  */
	 @RequestMapping("save")
	 @Token(remove = true)
	 public String saveSysMenu(@ModelAttribute Sysmenu sysmenu,RedirectAttributes attributes){
		 Sysmenu menu = sysmenuManagerService.getTopMenu();
		 String type = SpringMvcUtils.getParameter("type");
		 if (menu==null) {
			 Sysmenu topMenu = new Sysmenu();
			 topMenu.setParent(null);
			 topMenu.setParentIds("0");
			 topMenu.setName("顶级菜单");
			 sysmenuManagerService.save(topMenu);
		}
		 String parentId =  SpringMvcUtils.getParameter("parentId");
		 if (StringUtils.isNotEmpty(parentId)) {
			Sysmenu parentSysmenu = sysmenuManagerService.get(parentId);
			sysmenu.setParent(parentSysmenu);
			String oldParentIds = sysmenu.getParentIds();
			sysmenu.setParentIds(parentSysmenu.getParentIds()+sysmenu.getParent().getId()+",");
			sysmenuManagerService.save(sysmenu);
			//更新子节点 parentIds
			List<Sysmenu> list = sysmenuManagerService.getByParentIds(sysmenu.getId());
			for (Sysmenu childSysmenu : list) {
				childSysmenu.setParentIds(childSysmenu.getParentIds().replace(oldParentIds, sysmenu.getParentIds()));
				sysmenuManagerService.save(childSysmenu);
			}
			attributes.addFlashAttribute("msg", "菜单["+sysmenu.getName()+"]保存成功");
		}else {
			attributes.addFlashAttribute("msg", "创建菜单["+sysmenu.getName()+"]失败！无法获取上级菜单");
		}
		 attributes.addAttribute("top",	SpringMvcUtils.getParameter("top"));
		 attributes.addAttribute("left", SpringMvcUtils.getParameter("left"));
		 if ("1".equals(type)) {
			 return "redirect:/systemMenu/list.do?type=1";
		} else {
			 return "redirect:/systemMenu/list.do";
		}
		
	 }
	 
	 
	 /**
	  * @desc 删除菜单
	  * @param id  菜单主键id
	  * @param model
	  * @return 重定向到菜单列表页面
	  */
	 @RequestMapping("delete")
	 public String deleteSysmenu(String id,RedirectAttributes attributes){
		 Sysmenu sysmenu;
		 String type = SpringMvcUtils.getParameter("type");
		if (StringUtils.isNotEmpty(id)) {
			sysmenu = sysmenuManagerService.get(id);
		}else {
			sysmenu = new Sysmenu();
		}
		String name = sysmenu.getName();
		Sysmenu topSysmenu = sysmenuManagerService.getTopMenu();
		if (topSysmenu!=null&&topSysmenu.getId().equals(id)) {
			attributes.addFlashAttribute("msg", "删除菜单失败, 不允许删除顶级菜单或编号为空");
		}else {
			sysmenuManagerService.delete(id);
			attributes.addFlashAttribute("msg", "菜单["+name+"]删除成功!");
		}
		attributes.addAttribute("top",	SpringMvcUtils.getParameter("top"));
		attributes.addAttribute("left", SpringMvcUtils.getParameter("left"));
		
		if ("1".equals(type)) {
			return "redirect:/systemMenu/list.do?type=1";
		} else {
			return "redirect:/systemMenu/list.do";
		}
	 }
	 
	 /**
	  * 
	  * checkTag:
	  * 适用:新增和修改菜单信息时，ajax判断菜单标签在数据库中是否已经存在
	  * @return  返回true或false  json数据
	  * @exception 
	  * @since  1.0.0
	  */
	@ResponseBody
	@RequestMapping(value = "checkTag", produces = "application/json; charset=utf-8")
	public Boolean checkTag() {
		String oldTag = SpringMvcUtils.getParameter("oldTag");
		String tag = SpringMvcUtils.getParameter("tag");
		Boolean isExist = sysmenuManagerService.isTagUnique(tag, oldTag);
		return isExist;
	}
}
